import 'dart:async';
import 'package:flutter/material.dart';
import 'package:wayofdressing/contraints.dart';
import 'package:wayofdressing/components/choosebutton.dart';
import 'package:wayofdressing/components/verdisplaywindow.dart';
import 'package:wayofdressing/components/clothbox.dart';
import 'package:wayofdressing/components/clothboxes.dart';
import 'package:wayofdressing/components/inmenubutton.dart';
import 'package:wayofdressing/screens/add_cloth_screen.dart';
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wayofdressing/dio/ClothDio.dart';
import 'package:wayofdressing/dio/configureDio.dart';
import 'package:wayofdressing/good_method/decode_base64_to_bytes.dart';
import 'dart:typed_data'; // Uint8List 用于处理二进制数据
import 'package:wayofdressing/category/clothcategory.dart';

class ClosetScreen extends StatefulWidget {
  static final String id = 'closetscreen';

  @override
  State<ClosetScreen> createState() => _ClosetScreenState();
}

class _ClosetScreenState extends State<ClosetScreen> {
  int whoisactive = 1;
  List<Widget> widgetList = [];
  TextEditingController textController = TextEditingController();
  MenuController menuController = MenuController();
  bool isAddCloth = false;

  @override
  void initState() {
    super.initState();
    if (isAdd == true) {
      isAdd = false;
      _fetchClothData();
    }
    widgetList = clothCategoryWidgetList['上衣'] ?? [];
  }

  @override
  void dispose() {
    textController.dispose();
    super.dispose();
  }

  List<Widget> _createClothBoxes(Response<dynamic> response) {
    List<Widget> clothBoxes = [];
    List<dynamic> data = response.data['data']; // 根据你的 API 响应结构调整

    for (var item in data) {
      // 假设 item 中的 imageBytes 是 Base64 编码的字符串
      String? base64Image = item['imageBytes']; // 获取 Base64 编码的字符串
      Map<String, dynamic> cloth = {
        'userClothId': item['userClothId'] ?? '无',
        'name': item['clothName'] ?? '无',
        'category': item['category'] ?? '无',
        'subcategory': item['subcategory'] ?? '无'
      };
      if (base64Image != null && base64Image.isNotEmpty) {
        try {
          Uint8List imageBytes = decodeBase64ToBytes(base64Image);
          clothBoxes.add(
            ClothBox(
              hasImage: true,
              cloth: cloth,
              childWidget: Image.memory(imageBytes),
            ),
          );
        } catch (error) {
          print('Error decoding or displaying image: $error');
          clothBoxes.add(
            ClothBox(
              hasImage: false,
              cloth: cloth,
              childWidget: Container(
                child: Center(child: Text('没有图片')),
              ), // 占位或默认图像
            ),
          );
        }
      } else {
        // 处理 imageBytes 为 null 或空的情况
        clothBoxes.add(
          ClothBox(
            hasImage: false,
            cloth: cloth,
            childWidget: Container(
              child: Center(child: Text('没有图片')),
            ), // 占位或默认图像
          ),
        );
      }
    }
    return clothBoxes;
  }

  Future<void> _fetchClothData() async {
    try {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      int userId = prefs.getInt('id') ?? 0; // Fetch user ID from SharedPreferences
      clothCategoryWidgetList.clear();
      clothSubCategoryWidgetList.clear();

      for (String item in clothCategories) {
        for (String item1 in clothSubCategories[item]!) {
          Response<dynamic> response = await getClothByUserIdAndSubcategory(
            userId: userId,
            subcategory: item1,
            dio: dio,
          );
          setState(() {
            clothSubCategoryWidgetList[item1] = _createClothBoxes(response);
            if (!clothCategoryWidgetList.containsKey(item)) {
              clothCategoryWidgetList[item] = [];
            }
            clothCategoryWidgetList[item]!.add(ClothBoxes(
              clothesName: item1,
              clothes: clothSubCategoryWidgetList[item1]!,
            ));
          });
        }
      }
    } catch (e) {
      print('Error fetching category data: $e');
    }
    widgetList = clothCategoryWidgetList['上衣'] ?? [];
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfffffaf0),
      appBar: AppBar(
        backgroundColor: Color(0xfffffaf0),
        elevation: 0,
        toolbarHeight: 80,
        leadingWidth: 100,
        centerTitle: true,
        title: Text(
          '衣橱',
          style: TextStyle(
            color: Colors.black,
            fontWeight: FontWeight.bold,
            fontSize: kTopTitleFontSize,
          ),
        ),
        leading: Row(
          children: [
            SizedBox(
              width: 10,
            ),
            GestureDetector(
              onTap: () {
                Navigator.pop(context);
              },
              child: Transform.scale(
                scaleX: -1,
                child: Icon(
                  Icons.play_arrow_rounded,
                  size: kAppBarButtonSize,
                  color: Colors.black.withOpacity(0.5),
                ),
              ),
            ),
          ],
        ),
        actions: [
          MenuAnchor(
            controller: menuController,
            menuChildren: [
              InMenuButton(
                onPressed: () {
                  menuController.close();
                  if (!isAddCloth)
                    showModalBottomSheet(
                        isScrollControlled: true,
                        context: context,
                        builder: (context) => AddClothScreen()).then((_) {
                      setState(() {
                        isAddCloth = false;
                        if (isAdd == true) {
                          Navigator.pushReplacement(
                            context,
                            MaterialPageRoute(
                                builder: (context) => ClosetScreen()),
                          );
                        }
                      });
                    });
                  isAddCloth = true;
                },
                text: '添加衣服',
                alignment: Alignment.centerRight,
              ),
              InMenuButton(
                onPressed: () {},
                text: '背景设置',
                alignment: Alignment.centerRight,
              ),
              InMenuButton(
                onPressed: () {},
                text: '联系客服',
                alignment: Alignment.centerRight,
              ),
              InMenuButton(
                onPressed: () {},
                text: '问题咨询',
                alignment: Alignment.centerRight,
              ),
              InMenuButton(
                onPressed: () {},
                text: '设置',
                alignment: Alignment.centerRight,
              ),
            ],
            style: MenuStyle(
              shape: MaterialStateProperty.all(
                RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(25.0),
                ),
              ),
              alignment: Alignment(-3, 0.5),
              padding: MaterialStateProperty.all(EdgeInsets.all(15.0)),
              shadowColor: MaterialStateProperty.all(Colors.transparent),
              backgroundColor: MaterialStateProperty.all(
                Colors.black.withOpacity(0.4),
              ),
            ),
            builder: (BuildContext context, MenuController controller,
                Widget? child) {
              return GestureDetector(
                onTap: () {
                  if (controller.isOpen) {
                    controller.close();
                  } else {
                    controller.open();
                  }
                },
                child: Icon(
                  Icons.keyboard_control_rounded,
                  size: kAppBarButtonSize,
                  color: Colors.black,
                ),
              );
            },
          ),
          SizedBox(
            width: 20,
          )
        ],
      ),
      body: Stack(
        alignment: Alignment.center,
        children: [
          Column(
            children: [
              Container(
                height: 38,
                margin: EdgeInsets.symmetric(horizontal: 30),
                decoration: BoxDecoration(
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.2), // 阴影颜色和透明度
                      spreadRadius: 2, // 阴影扩展半径
                      blurRadius: 5, // 阴影模糊半径
                      offset: Offset(0, 5), // 阴影偏移量
                    ),
                  ],
                  borderRadius: BorderRadius.circular(25),
                  color: Colors.white,
                ),
                child: ListView.builder(
                  scrollDirection: Axis.horizontal,
                  itemCount: clothCategories.length,
                  itemBuilder: (context, index) {
                    return chooseButton(
                      isActive: whoisactive,
                      text: clothCategories[index],
                      listNumber: index,
                      onPressed: () {
                        setState(() {
                          whoisactive = index;
                          widgetList =
                              clothCategoryWidgetList[clothCategories[whoisactive]] ??
                                  [SizedBox()];
                        });
                      },
                    );
                  },
                ),
              ),
              SizedBox(
                height: 20,
              ),
              Expanded(
                child: VerDisplayWindow(
                  list: widgetList,
                ),
              ),
            ],
          ),
          Positioned(
            bottom: -10,
            child: Container(
              height: 50,
              width: 240,
              margin: EdgeInsets.symmetric(horizontal: 50, vertical: 30),
              decoration: BoxDecoration(
                color: Colors.black.withOpacity(0.3),
                borderRadius: BorderRadius.circular(40.0),
              ),
              child: TextField(
                controller: textController,
                showCursor: false,
                textAlign: TextAlign.center,
                cursorColor: Colors.black,
                style: TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                  fontSize: 22,
                ),
                decoration: InputDecoration(
                  suffixIcon: GestureDetector(
                    onTap: () {
                      setState(() {
                        textController.clear();
                      });
                    },
                    child: Icon(
                      Icons.search_rounded,
                      size: 50,
                      color: Colors.white,
                    ),
                  ),
                  border: InputBorder.none,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
